﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.RegularExpressions;

namespace Common.DataAnnotations
{
    /// <summary>
    /// 图片验证码
    /// </summary>
    public class ImgAuthCodeAttribute : ValidationAttribute
    {
        /// <summary>
        /// 图片验证码
        /// </summary>
        public ImgAuthCodeAttribute()
        {
            Required = true;
        }
        /// <summary>
        /// 图片验证码
        /// </summary>
        public ImgAuthCodeAttribute(bool required)
        {
            Required = required;
        }

        /// <summary>
        /// 是否为空
        /// </summary>
        public bool Required { get; set; }

        /// <inheritdoc/>
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                if (Required)
                {
                    if (string.IsNullOrEmpty(ErrorMessage))
                        ErrorMessage = "{0}不可为空！";
                    return false;
                }
                return true;
            }
            var temp = value.ToString();
            if (temp.Length != 5)
            {
                if (string.IsNullOrEmpty(ErrorMessage))
                    ErrorMessage = "{0}无效！";
                return false;
            }

            if (!Regex.IsMatch(temp, @"^[0-9a-zA-Z]{4}$"))
            {
                if (string.IsNullOrEmpty(ErrorMessage))
                    ErrorMessage = "{0}无效,必须是4位数字或字母！";
                return false;
            }
            return true;
        }
    }
}
